package com.ideal.tools.scheduler;

import com.ideal.tools.ssh.common.CommonProperties;
import com.ideal.tools.ssh.common.CommonTools;
import com.ideal.tools.ssh.common.OperationMarket;
import com.ideal.tools.ssh.context.ClusterContext;
import com.ideal.tools.ssh.entity.LinuxMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.util.List;

/**
 * Created by CC on 2016/3/30.
 */
public class DbFairScheduler {

    private static final Logger LOG = LoggerFactory.getLogger(DbFairScheduler.class);
    private boolean initialized;
    private static DocumentBuilder documentBuilder;
//    private DatabaseService databaseService;

    static {
        DocumentBuilderFactory docBuilderFactory =
                DocumentBuilderFactory.newInstance();
        docBuilderFactory.setIgnoringComments(true);
        try {
            documentBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("DocumentBuilder 初始化失败", e);
        }
    }


    /**
     * 跟新调度文件
     * @param context
     */
    public void initYarnFairScheduleFile(ClusterContext context){
        CommonProperties commonProperties= context.getCommonProperties();
        List<LinuxMachine> machines=context.getOriginalList();
        try {
            //根据传递值生成本地文件
            String fromPath=DbFairSchedulerTools.writeFairScheduleFileToLocal(commonProperties,documentBuilder);
            //最终放入地址
            String toPath = commonProperties.getProperty(CommonProperties.RM_SCHEDULE_XML_DES_PATH,"");
            //传递到mr 服务器
            String tmp_path = "/tmp/tmp_"+System.currentTimeMillis()+".tmp";

            //webapp 机器是脚本机器 放置执行脚本 所以是执行机器
            List<LinuxMachine> finalMachines = CommonTools.getMachineListByType(machines,context,
                    LinuxMachine.MachineType.ResourceManage);
            for(LinuxMachine machine :finalMachines){
                if(machine.getMachineType()== LinuxMachine.MachineType.ResourceManage){
                    //先把文件放到能登陆用户的 本地
                    CommonTools.upLoadLocalFile(machine.getSshAuthor(),fromPath,tmp_path);
                    //然后cp文件到最终目录
                    machine.initOperation(OperationMarket.ExeOneShellCMD("sudo cp "+tmp_path+" "+toPath));
                    //最后删除上传文件
                    machine.initOperation(OperationMarket.ExeOneShellCMD("rm -rf "+tmp_path));
                }
            }
            //重新设置 机器列表
            context.setMachineList(finalMachines);
            //执行
            context.doTheThing();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }


}
